//
//  NSFileManger+Ex.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/28.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation

class LocalFileManager: FileManager {
  
  // MARK: - Singleton
  
  static let shared = LocalFileManager()
  
  // MARK: - Private vars
  
  private var cachePath: String? = nil
  
  // MARK: - Private methods
  
  private func addSkipBackupAttribute(path: String) {
    var resourceValues = URLResourceValues()
    resourceValues.isExcludedFromBackup = true
    
    var url = URL(fileURLWithPath: path)
    do {
      try url.setResourceValues(resourceValues)
    } catch {
      loggingPrint(error.localizedDescription)
    }
  }
  
  // MARK: - Public vars
  
  var cacheRootPath: String? {
    get {
      return cachePath
    }
  }
  
  // MARK: - Public methods
  
  func prepareAudioCacheFolder() {
    if let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
      
      let path = "\(docPath)/Cache"
      
      func create() {
        do {
          try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
          addSkipBackupAttribute(path: path)
          cachePath = path
          loggingPrint("Cache dir created. \(path)")
        } catch let error {
          loggingPrint(error)
        }
      }
      
      var isDir: ObjCBool = false
      if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
        if isDir.boolValue == false {
          create()
        } else {
          cachePath = path
          loggingPrint("Cache dir exists. \(cachePath!)")
        }
      } else {
        create()
      }
    }
  }
}
